package com.io.viewgroup.image.adapter

import android.content.Context
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import androidx.viewbinding.ViewBinding
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.io.base.mvp.BaseAdapter
import com.io.base.mvp.BaseHolder
import com.io.commoncontrol.image.GlideRoundTransform
import com.io.commoncontrol.popwindow.CommonPopupWindow
import com.io.commonlib.helper.CommonDeviceHelper
import com.io.commonlib.helper.LogHelper
import com.io.viewgroup.Constans
import com.io.viewgroup.R
import com.io.viewgroup.databinding.ItemImageGroupViewBinding
import com.io.viewgroup.image.ImageGroupView
import com.io.viewgroup.image.activity.PreviewImageActivity
import com.io.viewgroup.image.interfaces.IOnClickPhotoAlbumListener
import com.io.viewgroup.image.interfaces.IOnClickTakePhotoListener

/**
 * Description:ImageGroupView的Adapter
 * 2021-03-20 17:03
 * @author LiuMin
 */
class ImageGroupViewAdapter(context: Context, imageGroupView: ImageGroupView) :
    BaseAdapter<String>(), CommonPopupWindow.ViewInterface {

    private val TAG = ImageGroupViewAdapter::class.java.simpleName
    private lateinit var popupWindow: PopupWindow
    private var contentView: View? = null
    private var mContext: Context
    private var mImageGroupView: ImageGroupView

    var isEditable: Boolean = false //控件是否可以编辑
    var defaultImage: Int = -1 //默认的占位符
    var delImage: Int = -1
    var isSupportAlbum: Boolean = false //是否支持从相册中选择图片
    var isSupportPreview: Boolean = false //是否支持预览
    var itemHeight: Float = 60f //每一项的高度
    var itemWidth: Float = 60f //每一项的宽度
    var itemMarginHorizontal: Float = 0f //这个列表的水平方向的margin
    var itemMarginVertical: Float = 0f //这个列表的垂直方向的margin
    var deviceWidth: Int = -1 //屏幕宽度
    var maxTotalCount: Int = -1 //控件最大图片张数
    var mOnClickTakePhotoListener: IOnClickTakePhotoListener? = null
    var mOnClickPhotoAlbumListener: IOnClickPhotoAlbumListener? = null

    init {
        mContext = context
        deviceWidth = CommonDeviceHelper().getDeviceWidthPixels(mContext)
        mImageGroupView = imageGroupView
        initPopupWindow()
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        parent: ViewGroup,
        viewType: Int
    ): ViewBinding {
        return ItemImageGroupViewBinding.inflate(inflater, parent, false)
    }

    override fun getItemViewType(position: Int): Int {
        return position
    }

    override fun setData(
        holder: BaseHolder,
        viewBinding: ViewBinding,
        data: String,
        position: Int
    ) {
        val binding = viewBinding as ItemImageGroupViewBinding
        val params = binding.imageGroupView.layoutParams as ViewGroup.MarginLayoutParams
        val paramsLayout =
            binding.layoutImageGroupView.layoutParams as ViewGroup.MarginLayoutParams
        paramsLayout.setMargins(
            itemMarginHorizontal.toInt(),
            itemMarginVertical.toInt(),
            itemMarginHorizontal.toInt(),
            itemMarginVertical.toInt()
        )
        params.width = itemWidth.toInt()
        params.height = itemHeight.toInt()
        binding.imageGroupView.layoutParams = params
        binding.layoutImageGroupView.layoutParams = paramsLayout
        if (isEditable) {
            editImageGroup(binding, position, data)
        } else {
            unEditImageGroup(binding, position, data)
        }
    }

    /**
     * 删除图片后刷新数据时会调用此方法
     */
    fun setImageList(list: List<String>?) {
        list?.let {
            mInfos = list.toMutableList()
        } ?: let {
            mInfos = mutableListOf()
        }
    }

    //region 私有方法
    /**
     * 初始化PopupWindow
     */
    private fun initPopupWindow() {
        contentView = LayoutInflater.from(mContext).inflate(R.layout.popup_image_group_view, null)
        popupWindow = PopupWindow(
            contentView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        popupWindow.isFocusable = true
        popupWindow.setBackgroundDrawable(BitmapDrawable())
        popupWindow.isOutsideTouchable = true
        popupWindow.isTouchable = true
        popupWindow.animationStyle = R.style.mypopwindow_anim_style
        val tvTakePhoto = contentView?.findViewById(R.id.tv_take_photo) as TextView
        val tvPhotoAlbums = contentView?.findViewById(R.id.tv_photo_albums) as TextView
        val tvCancel = contentView?.findViewById(R.id.tv_cancel) as TextView
        tvTakePhoto.setOnClickListener {
            hidePopupWindow()
            mOnClickTakePhotoListener?.onClickTakePhoto(mImageGroupView)
        }
        tvPhotoAlbums.setOnClickListener {
            hidePopupWindow()
            mOnClickPhotoAlbumListener?.onClickPhotoAlbum(mImageGroupView)
        }
        tvCancel.setOnClickListener {
            hidePopupWindow()
        }
    }

    /**
     * 显示PopupWindow
     */
    private fun showPopupWindow(){
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0)
    }

    /**
     * 隐藏PopupWindow
     */
    private fun hidePopupWindow(){
        if(popupWindow.isShowing){
            popupWindow.dismiss()
        }
    }

    /**
     * ImageGroupView设置可以编辑时，相关设置操作
     * 需要注意最后一条数据和其他数据的UI不一样
     */
    private fun editImageGroup(
        binding: ItemImageGroupViewBinding,
        position: Int,
        data: String
    ) {
        LogHelper.d(TAG, "editImageGroup--${mInfos.size}")
        if (position == mInfos.size - 1
            && (mInfos.size < maxTotalCount
                    || (mInfos.size == maxTotalCount && mInfos[mInfos.size - 1].equals(
                Constans.DEFAULT_VALUE_IMAGE_GROUP_VIEW
            )))
        ) {//最后一个条目需要显示默认图片,不需要显示删除按钮
            if (defaultImage != -1) {
                binding.imageGroupView.setImageResource(defaultImage)
            } else {
                binding.imageGroupView.setImageResource(R.drawable.camera_default)
            }
            binding.delGroupView.visibility = View.GONE
            binding.imageGroupView.setOnClickListener {
                if (isSupportAlbum) {//弹框显示选项
                    showPopupWindow()
                } else {//直接拍照
                    mOnClickTakePhotoListener?.onClickTakePhoto(mImageGroupView)
                }
            }
        } else {
            binding.delGroupView.visibility = View.VISIBLE
            LogHelper.d(TAG, "editImageGroup--${data}")
            Glide.with(mContext).load(data)
                .transform(CenterCrop(), GlideRoundTransform(mContext, 6))
                .into(binding.imageGroupView)
            if (delImage != -1) {
                binding.delGroupView.setImageResource(delImage)
            }
            binding.delGroupView.setOnClickListener {
                mImageGroupView.onFinishDelImageListener(position)
            }

            if (isSupportPreview) {//支持预览
                binding.imageGroupView.setOnClickListener {
                    priviewImages(position)
                }
            }
        }
    }

    /**
     * ImageGroupView设置不可以编辑时，相关设置操作
     */
    private fun unEditImageGroup(
        binding: ItemImageGroupViewBinding,
        position: Int,
        data: String
    ) {
        Glide.with(mContext).load(data).transform(CenterCrop(), GlideRoundTransform(mContext, 6))
            .into(binding.imageGroupView)
        if (isSupportPreview) {//支持预览
            binding.imageGroupView.setOnClickListener {
                priviewImages(position)
            }
        }
    }

    /**
     * 预览图片
     */
    private fun priviewImages(position: Int) {
        var intent = Intent(mContext, PreviewImageActivity::class.java)
        intent.putExtra("ImageGroupViewCurrentIndex", position)
        if (isEditable && mInfos.size < maxTotalCount) {
            mInfos.removeAt(mInfos.size - 1)
        }
        intent.putExtra("ImageGroupViewData", mInfos.toTypedArray())
        mContext.startActivity(intent)
    }

    override fun getChildView(view: View?, layoutResId: Int) {

    }
    //endregion
}